using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Google.Protobuf.Reflection;
using HuaXianQu.ProtoBuffEx.Runtime;
using UnityEngine;

namespace HuaXianQu.ProtoBuffEx.ToolEditor
{
    public class ProtoBasicTypeParse : IProtoTypeParse
    {
        private Dictionary<string, string> BasicTypes = new()
        {
            { "bool", "bool" },
            { "int", "int32" },
            { "uint", "uint32" },
            { "long", "int64" },
            { "ulong", "uint64" },
            { "float", "float" },
            { "double", "double" },
            { "string", "string" },
        };

        /// <summary>
        /// 根据 FieldDescriptor 获取基础类型
        /// </summary>
        /// <param name="fieldDescriptor"></param>
        /// <param name="fieldType"></param>
        /// <returns></returns>
        public bool GetRepeatedFieldElementType(FieldDescriptor fieldDescriptor, out Type fieldType)
        {
            fieldType = null;
            // 检查字段是否是 repeated 类型

            // 对于基础类型（例如 string, int32 等），返回相应的类型
            switch (fieldDescriptor.FieldType)
            {
                case FieldType.Int32:
                {
                    fieldType = typeof(int);
                }
                    break;
                case FieldType.UInt32:
                {
                    fieldType = typeof(uint);
                }
                    break;
                case FieldType.Int64:
                {
                    fieldType = typeof(long);
                }
                    break;
                case FieldType.UInt64:
                {
                    fieldType = typeof(ulong);
                }
                    break;
                case FieldType.String:
                {
                    fieldType = typeof(string);
                }
                    break;
                case FieldType.Bool:
                {
                    fieldType = typeof(bool);
                }
                    break;
                case FieldType.Double:
                {
                    fieldType = typeof(double);
                }
                    break;
                case FieldType.Float:
                {
                    fieldType = typeof(float);
                }
                    break;
                case FieldType.Enum:
                {
                    fieldType = fieldDescriptor.EnumType.ClrType;
                }
                    break;
                // 可以添加更多类型的映射
                default:
                {
                    if (fieldDescriptor.FieldType == FieldType.Message)
                    {
                        ProtoDebug.LogError($"{fieldDescriptor.Name} 的类型：{fieldDescriptor.FieldType}不是基础类型");
                    }
                    else
                    {
                        ProtoDebug.LogError($"{fieldDescriptor.Name} 的类型：{fieldDescriptor.FieldType}不被支持");
                    }

                    return false;
                }
            }
            
            // 如果不是 repeated 字段，返回 null
            return true;
        }

        public bool ConvertBrace(string value, string className,Type type, out object result)
        {
            result = null;

            if (type == typeof(string))
            {
                result = Regex.Replace(value, @"\\,|\\{|\\}", m =>
                {
                    // 判断是 \, 还是 \{
                    if (m.Value == @"\,")
                        return ","; // 替换 \, 为 ,
                    else if (m.Value == @"\{")
                        return "{"; // 替换 \{ 为 {
                    else if (m.Value == @"\}")
                    {
                        return "}"; // 替换 \{ 为 {
                    }
                    else
                    {
                        return m.Value; // 默认返回匹配的内容
                    }
                });
                return true;
            }

            try
            {
                result = Convert.ChangeType(value, type);
                return true;
            }
            catch (Exception e)
            {
                ProtoDebug.LogError($"ConvertBrace基础类型转换：{className}基础类型{type.Name}转换失败，原始数据：【{value}】==转换失败,err:{e}");
            }


            return false;
        }

        /// <summary>
        /// 获取基础类型
        /// </summary>
        /// <param name="type"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public bool ParseType(string type, out string result)
        {
            return BasicTypes.TryGetValue(type, out result);
        }
    }
}